<?php
namespace app\index\controller;

use app\index\model\User;
use think\Controller;
use think\Cookie;
use think\Session;
use think\Validate;

class LoginController extends Controller
{
    //前台登录首页
    public function index()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $rules = [
                'name'=>'require|max:30',
                'id'=>'require|number'
            ];
            $message = [
                'name.require' => '姓名不能为空',
                'name.max' => '姓名不能超过20个字符',
                'id.require' => '工号不能为空',
            ];
            $validate = new Validate($rules, $message);
            if (!$validate->check($data)) { // 验证不通过
                return $this->error($validate->getError()); //return back()->with('errors', $validate->getError());
            }
            $model = new User();
            //2.检测用户名和密码
            if ( !$user = $model->check_user(trim($data['id']), trim($data['name']))) {
                return $this->error('用户名或密码输入有误');
            }
            //3. 验证通过设置session
            Session::set('user_id', $user['id']);
            Session::set('name', $user['name']);
            Cookie::set('user_id', $user['id']);
            Cookie::set('name', $user['name']);
            $this->success('登录成功', 'index/index');
        }else {
            //return $this->fetch();
            return $this->fetch('login');
        }

    }
}
